package com.runfast.waimai.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.runfast.common.web.entity.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * ${DESCRIPTION}
 *
 * @author chenzheng
 * @create 2018-05-19 9:03
 **/
@RestController("uploadUtil")
@RequestMapping("/server/uploadUtil")
public class UploadUtil {
    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "Bku4MNJHn2m-qHPxZ4jDTkkV-tIw6U-u6Ex2mUrW";
    String SECRET_KEY = "eMSL04-fhF-IggfUsa_v87IcX_ehREMA0gVj3iCL";
    //要上传的空间
    String bucketname = "runfast";
    //上传到七牛后保存的文件名
    //String key ="/uplaod/"+String.valueOf(System.currentTimeMillis());
    //上传文件的路径
    //@Value("${web.upload-path}")
    //String FilePath = "d:/upload/my-java.png";
    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    Configuration cfg = new Configuration(Zone.zone2());
    //Zone z = Zone.zone1();
    //Configuration c = new Configuration(z);
    //创建上传对象
    UploadManager uploadManager = new UploadManager(cfg);

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    private static Set<String> imageSet = new HashSet<String>();
    static{

        imageSet.add(".png");
        imageSet.add(".jpg");
        imageSet.add(".jpeg");
        imageSet.add(".gif");
        imageSet.add(".bmp");
    }

    @PostMapping("/upload")
    public Result upload(@RequestParam("upfile")MultipartFile in, String filename) throws IOException {
        try {
            //调用put方法上传
            String newFileName = "upload/"+System.currentTimeMillis() + getExtention(in.getOriginalFilename());
            //String realPath = "/upload/";
            //File dstFile = new File(realPath,newFileName);
            //FileUtils.copyInputStreamToFile(in.getInputStream(), dstFile);
            Response res = uploadManager.put(in.getInputStream(), newFileName, getUpToken(),null,null);
            //打印返回的信息
            System.out.println(res.bodyString());

            if (res.isOK()) {
                DefaultPutRet putRet = res.jsonToObject(DefaultPutRet.class);
                System.out.println(putRet.key);
                Map<Object,Object> map=new HashMap<Object, Object>();
                map.put("key",putRet.key);
                return Result.ok(null,map);
                //return putRet.key;
            } else {
                return null;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
        return null;
         /* public static void main(String args[]) throws IOException{
           new UploadUtil().upload();
         }*/

    }
    /**
     * 获取文件后缀名
     * @param fileName
     * @return
     */
    private String getExtention(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if(pos>0){
            fileName = fileName.substring(pos);
        }
        return fileName;
    }

    /*@PostMapping("/upload")
    public Result upload(File in, String filename) throws IOException {
        try {
            //调用put方法上传
            Response res = uploadManager.put(in, filename, getUpToken());
            //打印返回的信息
            //System.out.println(res.bodyString());
            if (res.isOK()) {
                DefaultPutRet putRet = res.jsonToObject(DefaultPutRet.class);
                Map<Object,Object> map=new HashMap<Object, Object>();
                map.put("key",putRet.key);
                return Result.ok(null,map);
                //return putRet.key;
            } else {
                return null;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
        return null;
         *//* public static void main(String args[]) throws IOException{
           new UploadUtil().upload();
         }*//*

    }*/

    /*public void upload() throws IOException {
        try {
            //调用put方法上传
            Response res = uploadManager.put(FilePath, key, getUpToken());
            //打印返回的信息
            //System.out.println(res.bodyString());
            if (res.isOK()) {
                DefaultPutRet putRet = res.jsonToObject(DefaultPutRet.class);
                System.out.println(res.bodyString());
                System.out.println(putRet.key);
                //Map<Object,Object> map=new HashMap<Object, Object>();
                //map.put("key",putRet.key);
                //return Result.ok(null,map);
                //return putRet.key;
            } else {
                //return null;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
     }
    public static void main(String args[]) throws IOException{
        new UploadUtil().upload();
    }*/
}